package com.ezhuan.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class IpLocalUtil
{

	final static String key = "595c7e3214c87f8bf906e1b81511a1de";
	final static String url = "http://apis.juhe.cn/ip/ip2addr";
	final static String dtype = "json";

	public static String sendGet(String ip)
	{
		String urls = url + "?key=" + key + "&dtype=" + dtype + "&ip=" + ip;
		String message1 = "";
		BufferedReader in = null;
		InputStream is = null;
		URLConnection connection = null;
		InputStreamReader isread = null;
		try
		{
			URL realUrl = new URL(urls);
			connection = realUrl.openConnection();

			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.setConnectTimeout(800);
			connection.connect();

			Map<String, List<String>> map = connection.getHeaderFields();
			String str1;
			for (Iterator localIterator = map.keySet().iterator(); localIterator
					.hasNext(); str1 = (String) localIterator.next())
			{
			}
			is = connection.getInputStream();
			isread = new InputStreamReader(is, "utf-8");
			in = new BufferedReader(isread);
			String line;
			while ((line = in.readLine()) != null)
			{
				message1 = message1 + line;
			}

		} catch (Exception e)
		{

		} finally
		{
			try
			{
				if (in != null)
				{
					in.close();
				}
				if (isread != null)
				{
					isread.close();
				}
				if (is != null)
				{
					is.close();
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}

		}
		ConstatFinalUtil.LOGGER.info("ip归属地:ip:{},结果:{}",ip,message1);
		return message1;
	}

	public static void main(String[] args)
	{
		sendGet("123.116.40.199");
		sendGet("127.0.0.1");
	}
}
